#include "userclient.h"
#include <QAbstractSocket>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonParseError>

#include "database/dataquery.h"
UserClient::UserClient(qintptr descrip,QObject *parent) : QObject(parent)
{
    this->descriptor=descrip;
    query=DataQuery::instence();
    init_cmd();
}
UserClient::~UserClient()
{

}
void UserClient::init_cmd()
{
    cmd.insert("get_dev_type",1);
    cmd.insert("get_house_list",2);
    cmd.insert("get_device_list",3);
    cmd.insert("get_cmd_by_dev",4);
    cmd.insert("get_scene_list",5);
    cmd.insert("get_cmd_by_scene",6);
    cmd.insert("get_task_list",7);
    cmd.insert("add_devtype",21);
    cmd.insert("add_house",22);
    cmd.insert("add_device",23);
    cmd.insert("add_cmd",24);
    cmd.insert("add_scene",25);
    cmd.insert("add_cmdlist",26);
    cmd.insert("add_condition",27);
    cmd.insert("add_timing",28);

}
//create client by socket descriptor
void UserClient::start()
{
    client=new QTcpSocket;
    if (!client->setSocketDescriptor(descriptor))
    {
        return;
    }
    connect(client,&QTcpSocket::disconnected,this,&UserClient::disconsoket);
    connect(client,&QTcpSocket::readyRead,this,&UserClient::readyread);
    client->open(QIODevice::ReadWrite);
}
void UserClient::disconsoket()
{
    qDebug()<<"net work disconnected !!";
    emit this->offline(descriptor);
}
void UserClient::readyread()
{
    QByteArray buff= client->readLine();
    emit sendtoserver(this->descriptor,buff);
}
void UserClient::analisys(QByteArray arr)
{
    QJsonParseError json_error;
    QJsonDocument::fromJson(arr,&json_error);
}

void UserClient::writedata(QByteArray data)
{
    if(client==nullptr||!client->isOpen()||!client->isWritable())
    {
        return;
    }
    client->write(data);
}
qintptr UserClient::getdescriptor() const
{
    return this->descriptor;
}



